package com.googlecode.yoohoo.xmppcore.protocol.stanza;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.yoohoo.xmppcore.protocol.XmlLangText;
import com.googlecode.yoohoo.xmppcore.protocol.parsing.ProtocolKey;
import com.googlecode.yoohoo.xmppcore.protocol.translation.IXmlWriter;

public class Presence extends Stanza {
	public static final ProtocolKey PROTOCOL_KEY = new ProtocolKey("presence", null);
	
	private String show;
	private List<XmlLangText> status;
	private Integer priority;
	
	private static String[] PRESENCE_TYPES;
	private static String[] PRESENCE_SHOWS;
	
	static {
		PresenceType[] presenceTypes = PresenceType.values();
		PRESENCE_TYPES = new String[presenceTypes.length];
		for (int i = 0; i < presenceTypes.length; i++) {
			PRESENCE_TYPES[i] = presenceTypes[i].toString();
		}
		
		PresenceShow[] presenceShows = PresenceShow.values();
		PRESENCE_SHOWS = new String[presenceShows.length];
		for (int i = 0; i < presenceShows.length; i++) {
			PRESENCE_SHOWS[i] = presenceShows[i].toString();
		}
	}
	
	public Presence() {
		status = new ArrayList<XmlLangText>();
	}

	public String getShow() {
		return show;
	}

	public void setShow(String show) {
		if (show == null)
			throw new IllegalArgumentException("Null presence show");
		
		for (PresenceShow presenceShow : PresenceShow.values()) {
			if (presenceShow.toString().equals(show)) {
				this.show = show;
				
				return;
			}
		}
		
		throw new IllegalArgumentException(String.format("'%s' is an invalid presence show", show));
	}

	public List<XmlLangText> getStatus() {
		return status;
	}

	public void setStatus(List<XmlLangText> status) {
		this.status = status;
	}

	public Integer getPriority() {
		return priority;
	}

	public void setPriority(Integer priority) {
		this.priority = priority;
	}
	
	@Override
	protected String[] getValidTypes() {
		return PRESENCE_TYPES;
	}

	@Override
	public StanzaKind getStanzaKind() {
		return StanzaKind.PRESENCE;
	}

	@Override
	protected void doToXml(IXmlWriter writer) {
		if (show != null) {
			writer.writeStartElement("show");
			writer.writeCharacters(show, false);
			writer.writeEndElement();
		}
		
		if (status != null) {
			for (XmlLangText aStatus : status) {
				writer.writeStartElement("status");
				if (aStatus.getXmlLang() != null) {
					writer.writeAttribute("xml:lang", aStatus.getXmlLang());
				}
				writer.writeCharacters(aStatus.getText());
				writer.writeEndElement();
			}
		}
		
		if (priority != null) {
			writer.writeStartElement("priority");
			writer.writeCharacters(priority.toString());
			writer.writeEndElement();
		}
	}
}
